package exercise22;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class Exercise22_6 extends JFrame
	implements ActionListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField jtfInput = new JTextField(16);
	private JLabel jlbName = new JLabel("Enter a number: ");
	private JTextArea jtaOutput = new JTextArea();
	
	private JButton jbtSort = new JButton("Sort");
	private JButton jbtShuffle = new JButton("Shuffle");
	private JButton jbtReverse = new JButton("Reverse");
	
	private LinkedHashSet<Integer> linkedhashSet = new LinkedHashSet<Integer>();
	private ArrayList<Integer> arrayList = new ArrayList<Integer>();
	private String tempNumbers = "";
	
	public void actionPerformed(ActionEvent e){
		if (e.getSource() == jtfInput) {
			//接收输入数据
			arrayList.clear();
			//用规则集去重
			linkedhashSet.add(Integer.parseInt(jtfInput.getText()));
			//将规则集中的数据存入链表
			arrayList.addAll(linkedhashSet);
		}
		else if (e.getSource() == jbtSort) {
			//对链表中的数据进行升序排序
			//清除规则集中的数据，防止其干扰之后的处理结果
			linkedhashSet.clear();
			//对链表中的数据进行升序排序
			Collections.sort(arrayList);
			linkedhashSet.addAll(arrayList);
		}
		else if (e.getSource() == jbtShuffle) {
			linkedhashSet.clear();
			//打乱链表中的数据
			Collections.shuffle(arrayList);
			linkedhashSet.addAll(arrayList);
		}
		else if (e.getSource() == jbtReverse) {
			linkedhashSet.clear();
			//将链表中的数据进行翻转镜像
			Collections.reverse(arrayList);
			linkedhashSet.addAll(arrayList);
		}
		else{
			System.out.println("Nothing");
		}
		
		//显示处理结果
		tempNumbers = "";
		for (Integer i:arrayList) {
			tempNumbers = tempNumbers + i.toString()+ " " ;
		}
		jtaOutput.setText(tempNumbers);
	}
	
	public Exercise22_6(){
		JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
		p1.add(jlbName);
		p1.add(jtfInput);
		
		JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
		p2.add(jbtSort);
		p2.add(jbtShuffle);
		p2.add(jbtReverse);
		
		setLayout(new BorderLayout());
		add(p1, BorderLayout.NORTH);
		add(jtaOutput, BorderLayout.CENTER);
		add(p2, BorderLayout.SOUTH);
		
		jtfInput.addActionListener(this);
		jbtSort.addActionListener(this);
		jbtShuffle.addActionListener(this);
		jbtReverse.addActionListener(this);
		
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame frame = new Exercise22_6();
		frame.setTitle("Exercise22_6");
		frame.setSize(400, 200);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		
	}

}
